<?php 
include_once "../library/Controller.php";

class Users extends Controller
{
	function __construct()
	{
		//important to call initialize superclass
		parent::__construct();

		// use data to store the GET method
		$data 	= $_GET;

		$action = $data['action'];

		// switch actions
		if ($action == 'insert')
		{
			$this->insertUser($data);
		}	
		else if ($action == 'delete')
		{
			$this->deleteUser($data);
		}
		else if ($action == 'manage')
		{
			$create 	= $data['create'];
			$drop	 	= $data['drop'];

			if ( ! empty($create))
			{
				$this->createTable();
			}
			else if ( ! empty($drop))
			{
				$this->dropTable();
			}
		}
	}


	function run()
	{
		$data = array();
		$data['title'] = "Users";
		$data['users'] = $this->getUsers();
		
		// display the users view
		$this->load('users_view.php', $data);
	}

	function getUsers()
	{
		$result = $this->db->query('SELECT * from users');

		if (! $result)
			return;

		$userArray = array();

		while ($row = $result->fetchArray())
		{
			$userArray[] = array(
				"uid" 		=> $row["uid"],
				"username" => $row["username"],
				"password" => $row["password"],
			);
		}

		return $userArray;
	}

	//function insertUser($username, $password)
	function insertUser($data = array())
	{
		$username = $data['username'];
		$password = $data['password'];

		$sql = "INSERT INTO users (
			username,
			password
			) VALUES (
				'$username',
				'$password'
			);";

		if ( ! $this->db->exec($sql))
		{
			echo "$sql<br>
				insert failed!<br>
				try this command: \$chmod -R a+w ./db";
			exit();
		}
	}

	function deleteUser($data)
	{
		$uid = $data['uid'];

		$sql = "DELETE FROM users
			WHERE uid = $uid;";

		if ( ! $this->db->exec($sql))
		{
			echo "$sql<br>
				delete failed!<br>";
			exit();
		}
	}

	function createTable()
	{
		$sql = "CREATE TABLE users
			(
				uid INTEGER PRIMARY KEY,
				username TEXT,
				password TEXT
			);";

		if ( ! $this->db->exec($sql))
		{
			echo "$sql<br>
				create failed!<br>";
			exit();
		}
	}

	function dropTable()
	{
		$sql = "DROP TABLE users;";

		if ( ! $this->db->exec($sql))
		{
			echo "$sql<br>
				drop failed!<br>";
			exit();
		}
	}

}

// execute the class
$users = new Users();
$users->run();

